package meihua.stopcarapp.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;

import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import meihua.mylibrary.base.BaseActivity;
import meihua.stopcarapp.R;
import meihua.stopcarapp.app.UserConfig;
import meihua.stopcarapp.bean.ParkingEntity;
import meihua.stopcarapp.bean.result.LadvanceResult;
import meihua.stopcarapp.bean.result.LockResult;
import meihua.stopcarapp.bean.result.UnLadvanceResult;
import meihua.stopcarapp.bean.result.UserResult;
import meihua.stopcarapp.model.ParkingModel;
import meihua.stopcarapp.presenter.ParkingPresenter;
import meihua.stopcarapp.presenter.contract.ParkingContract;
import meihua.stopcarapp.utils.ToastUtil;
import meihua.stopcarapp.utils.UIUtils;
import meihua.stopcarapp.widget.XCRoundImageView;
import meihua.stopcarapp.widget.dialog.OrderDialog;


@RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public class MainActivity extends BaseActivity<ParkingPresenter, ParkingModel>
        implements ParkingContract.View, SensorEventListener,
        LocationSource, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter {

    @Bind(R.id.activity_main_layout)
    RelativeLayout activityMainLayout;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.start_drawer)
    RelativeLayout startDrawer;
    @Bind(R.id.left_drawer_icon)
    XCRoundImageView leftDrawerIcon;
    @Bind(R.id.left_drawer_username)
    TextView leftDrawerUsername;
    @Bind(R.id.left_drawer_phone)
    TextView leftDrawerPhone;
    @Bind(R.id.left_drawer_status)
    TextView leftDrawerStatus;
    @Bind(R.id.left_drawer_item1_yuan)
    TextView leftDrawerYuan;
    @Bind(R.id.activity_main_map)
    MapView mainMap;
    @Bind(R.id.activity_main_btn_location)
    ImageView btn_location;
    @Bind(R.id.activity_main_top_news)
    TextView topNewsTV;
    @Bind(R.id.toolbar_left)
    ImageView toolbarLeft;
    @Bind(R.id.toolbar_center)
    TextView toolbarCenter;
    @Bind(R.id.toolbar_right)
    ImageView toolbarRight;
    @Bind(R.id.activity_main_stop_tv)
    TextView activityMainStopTV;

    MyLocationStyle myLocationStyle;//定位蓝点样式类
    AMap aMap;

    //定位方向
    private SensorManager mSM;
    private Sensor mSensor;
    //路线相关
    public LatLonPoint fromLLP;
    public LatLonPoint endLLP;
    //定位相关
    public AMapLocationClient mlocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public AMapLocationListener mLocationListener;
    public int islocation = 0;
    //预约相关
    private Marker marker_selected = null;
    private ParkingEntity parking;
    LadvanceResult ladvanceResult;
    String order_num;
    //marker点相关
    private List<ParkingEntity> parkings;

    /**
     * 入口
     *
     * @param activity
     */
    public static void startAction(Activity activity) {
        Intent intent = new Intent(activity, MainActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM( this, mModel );
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void initView(Bundle savedInstanceState) {

//        mPresenter.getParkingListRequest("116.40355","39.9000");
        toolbarLeft.setImageResource(R.mipmap.ic_toolbar_left);
        toolbarRight.setVisibility(View.VISIBLE);
        toolbarCenter.setText("易停");
        //获取当前位置信息
        initRouteSearch();
        //陀螺仪支持
        mSM = (SensorManager)getSystemService(SENSOR_SERVICE);
        mSensor = mSM.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        mSM.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_UI);//注册回调函数
        initMapLocationStyle(savedInstanceState);
        aMap.setInfoWindowAdapter(this);
        aMap.setOnMarkerClickListener(this);
        //重新定位
//        btn_location.performClick();
    }

    //定位蓝点
    void initMapLocationStyle(Bundle savedInstanceState){
        mainMap.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) aMap = mainMap.getMap();

        aMap.getUiSettings().setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);//缩放按钮放到右侧中间
        if (myLocationStyle == null)
            myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory. //设置定位蓝点图标
                fromResource(R.mipmap.navi_map_gps_locked));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//定位一次
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));// 设置缩放级别
        aMap.setMyLocationEnabled(true);
        //获取当前位置信息
//        initRouteSearch();
    }

    //定位信息
    void initRouteSearch() {
        //初始化定位
        mlocationClient = new AMapLocationClient(getApplicationContext());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //异步获取定位结果
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        if (fromLLP == null) {
                            fromLLP = new LatLonPoint(amapLocation.getLatitude(),amapLocation.getLongitude());
                        }else {
                            fromLLP.setLongitude(amapLocation.getLongitude());
                            fromLLP.setLatitude(amapLocation.getLatitude());
                        }
                        if (islocation <2 ){
                            btn_location.performClick();
                            islocation++;
                        }
//                        topNewsTV.setText(fromLLP.getLongitude()+","+fromLLP.getLatitude());
//                        ToastUtil.showShort(MainActivity.this,fromLLP.getLongitude()+","+fromLLP.getLatitude());
                    }
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        };
        //设置定位回调监听
        mlocationClient.setLocationListener(mLocationListener);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval( 5000 );
        //开启缓存机制
        mLocationOption.setLocationCacheEnable( true );
        //设置定位参数
        mlocationClient.setLocationOption( mLocationOption );
        mLocationOption.setLocationCacheEnable(true);
        //启动定位
        mlocationClient.startLocation();

    }

    @OnClick({R.id.activity_main_btn_location, R.id.activity_main_btn_navigation, R.id.left_drawer_item0,
            R.id.left_drawer_item1, R.id.left_drawer_item2, R.id.left_drawer_item3, R.id.left_drawer_item4,
            R.id.left_drawer_item5, R.id.toolbar_left, R.id.toolbar_right, R.id.activity_main_news,
            R.id.activity_main_btn_stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_main_news:
//                checkStopCard();

                break;
            case R.id.activity_main_btn_stop:
                if (!checkStopCard()) return; //用户不合法直接返回
                stopCar();
                break;
            case R.id.activity_main_btn_location:
//                initRouteSearch();
//                Log.i("ligaozeng","activity_main_btn_location:"+fromLLP.getLongitude()+","+fromLLP.getLatitude());
                if (fromLLP != null)
                mPresenter.getParkingListRequest(fromLLP.getLongitude()+"",fromLLP.getLatitude()+"");
                aMap.moveCamera(CameraUpdateFactory.zoomTo(15));// 设置缩放级别
                mainMap.setRotation(0);
                aMap.setMyLocationStyle(myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE));
                break;
            case R.id.activity_main_btn_navigation:

                break;
            case R.id.toolbar_left:
                drawerLayout.openDrawer( startDrawer );
                break;
            case R.id.toolbar_right:
                RepairActivity.startAction( MainActivity.this );
                break;
            case R.id.left_drawer_item0:
                if (null == UserConfig.USER_ENTITY){
                    LoginAcivity.startAction(MainActivity.this);
                    ToastUtil.showShort(this,"您还未登陆，请先登陆");
                }else {
                    //头像
                    UserInformationActivity.startAction(MainActivity.this);
                }
                break;
            case R.id.left_drawer_item1:
                //钱包
                MyWalletActivity.startAction( MainActivity.this );
                break;
            case R.id.left_drawer_item2:
                //邀请
                InviteActivity.startAction(MainActivity.this);
                break;
            case R.id.left_drawer_item3:
                //车位共享
                SharedParkActivity.startAction(MainActivity.this);
                break;
            case R.id.left_drawer_item4:
                ToastUtil.showShort( this, "5" );
                break;
            case R.id.left_drawer_item5:
                DepositPayActivity.startAction(this);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        btn_location.performClick();
        mPresenter.sendGetUser(UserConfig.USER_ENTITY.getUser_id(),UserConfig.USER_ENTITY.getUser_phone());
        drawerLayout.closeDrawer(startDrawer);
        mainMap.onResume();
        //没登陆
        if (UserConfig.USER_ENTITY == null) {
            activityMainStopTV.setText("登陆");
            topNewsTV.setText("您还未登录，点击登陆！");
            return;
        }
        if (null != UserConfig.USER_ENTITY.getUser_photo() || "".equals(UserConfig.USER_ENTITY.getUser_photo())){
            //用户已经上传过头像
        }
        leftDrawerYuan.setText(UserConfig.USER_ENTITY.getUser_balance());
        leftDrawerPhone.setText(UserConfig.USER_ENTITY.getUser_phone());
        double deposit =Double.parseDouble(UserConfig.USER_ENTITY.getUser_deposit());
        //没交押金
        if (deposit == 0){
            activityMainStopTV.setText("交押金");
            topNewsTV.setText("您还未缴纳押金，点我快速缴纳！");
            return;
        }
        //没认证
        if ("".equals(UserConfig.USER_ENTITY.getUser_idcard()) || null == UserConfig.USER_ENTITY.getUser_idcard()){
            activityMainStopTV.setText("认证");
            topNewsTV.setText("您还未认证，点击认证！");
            return;
        }
        leftDrawerUsername.setText(UserConfig.USER_ENTITY.getUser_name());
        double balance = Double.parseDouble(UserConfig.USER_ENTITY.getUser_balance());
        //余额不足
        if (balance <=0 ){
            activityMainStopTV.setText("充值");
            topNewsTV.setText("您的余额不足，点击充值！");
            return;
        }
        topNewsTV.setText("选择车位，点按钮预约或停车！");

    }

    //查看用户停车资格
    public boolean checkStopCard() {
        //没登陆
        if (UserConfig.USER_ENTITY == null) {
            LoginAcivity.startAction(MainActivity.this);
            return false;
        }
        Double deposit =Double.parseDouble(UserConfig.USER_ENTITY.getUser_deposit());
        //没交押金
        if (deposit == 0){
            DepositPayActivity.startAction(MainActivity.this);
            return false;
        }
        //没认证
        if ("".equals(UserConfig.USER_ENTITY.getUser_idcard()) || null == UserConfig.USER_ENTITY.getUser_idcard()){
            ToastUtil.showShort(MainActivity.this,"认证");
            return false;
        }
        double balance = Double.parseDouble(UserConfig.USER_ENTITY.getUser_balance());
        //余额不足
        if (balance <=0 ){
            ToastUtil.showShort(MainActivity.this,"充值");
            return false;
        }
        return true;
    }

    //停车按钮
    void stopCar(){
        //如果时预约中，再次点击，直接开锁
        if ("1".equals(UserConfig.USER_ENTITY.getUser_car_status())){
            //开锁
            mPresenter.getsecdOpenLockRequest(UserConfig.USER_ENTITY.getUser_phone(),UserConfig.USER_ENTITY.getPark_list_info().getParking_list_num());
            //修改缓存信息
            UserConfig.USER_ENTITY.setUser_car_status("2");
//            StopCarActivity.startAction(MainActivity.this,order_num);
            return;
        }
        if (marker_selected == null){
            ToastUtil.showShort(MainActivity.this,"请选择车位");
            return;
        }
        //距离小于50米
        if (Integer.parseInt(marker_selected.getSnippet()) <= 50){
            //开锁
            mPresenter.getsecdOpenLockRequest(UserConfig.USER_ENTITY.getUser_phone(),parking.getParking_list_num());
            //修改缓存信息
            UserConfig.USER_ENTITY.setUser_car_status("2");
//            StopCarActivity.startAction(MainActivity.this,order_num);
        }else {
            //预约
            mPresenter.getsecdLadvanceRequest(UserConfig.USER_ENTITY.getUser_phone(),parking.getParking_list_num());
            //修改缓存信息
            UserConfig.USER_ENTITY.setUser_car_status("1");
            aMap.clear();
            final OrderDialog orderDialog = new OrderDialog(MainActivity.this,R.style.main_order_Dialog);
            orderDialog.setOnOrderClickListener(new OrderDialog.OnOrderClickListener() {
                @Override
                public void cancleClick() {
                    //取消预约
                    mPresenter.getsecdUnLadvanceRequest(ladvanceResult.getAdv_id(),UserConfig.USER_ENTITY.getUser_phone(),parking.getParking_list_num());
                    //修改缓存信息
                    UserConfig.USER_ENTITY.setUser_car_status("0");
                    btn_location.performClick();
                    orderDialog.dismiss();
                }
                //预约后开始导航
                @Override
                public void starcClick() {
                    //开始
                    if (fromLLP == null){
                        ToastUtil.showShort(MainActivity.this,"定位失败，请稍后重试！");
                        return;
                    }
                    if (marker_selected == null){
                        ToastUtil.showShort(MainActivity.this,"请选择终点！");
                        return;
                    }
                    Bundle bundle = new Bundle();
                    bundle.putDouble("s_latitude",fromLLP.getLatitude());
                    bundle.putDouble("s_longitude",fromLLP.getLongitude());
                    bundle.putDouble("e_latitude",marker_selected.getPosition().latitude);
                    bundle.putDouble("e_longitude",marker_selected.getPosition().longitude);
//                    NaviActivity.startAction(MainActivity.this,bundle);
                    Intent intent = new Intent(MainActivity.this,NaviActivity.class);

                    startActivityForResult(intent,1);
                }
            });
            orderDialog.show();
        }
    }

    //地图定位箭头方向
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
            float degree = event.values[0];
            float bearing = aMap.getCameraPosition().bearing;
            if (degree + bearing > 360)
                aMap.setMyLocationRotateAngle( degree + bearing - 360 );// 设置小蓝点旋转角度
            else
                aMap.setMyLocationRotateAngle( degree + bearing );//
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void returnUserInfo(UserResult userEntity) {
        UserConfig.USER_ENTITY = userEntity;
        if ("1".equals(userEntity.getUser_car_status())){
            activityMainStopTV.setText("立即停车");
        }
        //正在使用
        if ("2".equals(userEntity.getUser_car_status())){
            StopCarActivity.startAction(MainActivity.this,userEntity.getPark_list_info().getOrder_num());
        }
        //未缴费
        if ("3".equals(userEntity.getUser_car_status())){
            Bundle bundle = new Bundle();
            bundle.putString("order_monry",UserConfig.USER_ENTITY.getPark_list_info().getOrder_monry());
            OrderEcodeActivity.startAction(MainActivity.this,bundle);
        }
    }

    //服务器返回的数据
    @Override
    public void returnParkingList(List<ParkingEntity> listparking) {
        this.parkings = listparking;
        if (parkings == null) {
            ToastUtil.showShort( MainActivity.this, "数据为空" );
            return;
        }
        Log.i("ligaozeng","returnParkingList:"+parkings.size());
        for (ParkingEntity entity:parkings) {
            aMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                            .decodeResource(getResources(),R.mipmap.ic_main_marker_black)))
                    .position(new LatLng(entity.getParking_list_latitude_double(),entity.getParking_list_longitude_double()))
                    .title(entity.getParking_position_position()+","+entity.getParking_position_name())
                    .snippet(entity.getDistance()+""));
        }
    }

    @Override
    public void returnsecdLadvance(LadvanceResult ladvance) {
        ToastUtil.showShort(MainActivity.this,ladvance.getParking_list_num());
        ladvanceResult = ladvance;
    }

    @Override
    public void returnsecdUnLadvance(UnLadvanceResult ladvance) {
        ToastUtil.showShort(MainActivity.this,ladvance.getParking_list_num());
    }

    //解锁返回值
    @Override
    public void returnOpenLock(LockResult ladvance) {
        UserConfig.USER_ENTITY.getPark_list_info().setOrder_num(ladvance.getOrder_num());
        order_num = ladvance.getOrder_num();
        StopCarActivity.startAction(MainActivity.this,order_num);
        ToastUtil.showShort(this,"开锁成功！"+ladvance.getOrder_num());
    }

    //自定义infowindow
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindowView = UIUtils.inflate(R.layout.marker_info_window);

        String[] titles = marker.getTitle().split(",");
        ((TextView)infoWindowView.findViewById(R.id.info_window_text1)).
                setText(titles[0]);
        ((TextView)infoWindowView.findViewById(R.id.info_window_text2)).
                setText(titles[1]);
        ((TextView)infoWindowView.findViewById(R.id.info_window_text3)).
                setText("（距离您"+marker.getSnippet()+"米）");
        (infoWindowView.findViewById(R.id.info_window_btn1)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开始
                if (fromLLP == null){
                    ToastUtil.showShort(MainActivity.this,"定位失败，请稍后重试！");
                    return;
                }
                if (marker_selected == null){
                    ToastUtil.showShort(MainActivity.this,"请选择终点！");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putDouble("s_latitude",fromLLP.getLatitude());
                bundle.putDouble("s_longitude",fromLLP.getLongitude());
                bundle.putDouble("e_latitude",marker_selected.getPosition().latitude);
                bundle.putDouble("e_longitude",marker_selected.getPosition().longitude);
                NaviActivity.startAction(MainActivity.this,bundle);
            }
        });
        return infoWindowView;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    //地图上标记点的点击事件
    @Override
    public boolean onMarkerClick(Marker marker) {
        marker_selected = marker;
        if (Integer.parseInt(marker.getSnippet())<=50)
            activityMainStopTV.setText("立即停车");
        else activityMainStopTV.setText("立即预约");
        //车位信息
        LatLng latLng = marker.getPosition();
        String longitude = latLng.longitude+"";
        String latitude = latLng.latitude+"";
        for (ParkingEntity parkingEntity:parkings){
            if (longitude.equals(parkingEntity.getParking_list_longitude())
                    && latitude.equals(parkingEntity.getParking_list_latitude())){
                //经纬度相同认为选择的是这个点
                parking = parkingEntity;
                ToastUtil.showShort(MainActivity.this,parking.getParking_list_num());
            }
        }

//        if (marker_selected == null){
//            marker_selected = marker;
//            endLLP = new LatLonPoint( marker.getPosition().latitude, marker.getPosition().latitude );
//            return false;
//        }else {
//            marker_selected = null;
//            return true;
//        }

        return false;
    }

    /**
     * rxjava + retrofit
     *
     * @param title
     */
    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {

    }

    /**
     * 定位功能
     * @param onLocationChangedListener
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    /**
     * 生命周期
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mainMap != null)
            mainMap.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mainMap.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mainMap.onSaveInstanceState(outState);
    }

}
